package com.cedifie.lendapp.ui.steps.fm

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.cedifie.lendapp.R
import com.cedifie.lendapp.databinding.FmStepAccountBinding
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.mvp.MvpFm
import com.cedifie.lendapp.ui.steps.act.CedStepAct
import com.cedifie.lendapp.ui.steps.adapter.CedStepAccountAdapter
import com.cedifie.lendapp.ui.steps.impl.CedAccountPresenterImpl
import com.cedifie.lendapp.ui.steps.view.ICedAccountView
import com.cedifie.lendapp.utils.decoration.LinearSpacingItemDecoration
import com.cedifie.lendapp.utils.dialog.BindCardAddDialog
import com.cedifie.lendapp.utils.dialog.BindCardDeleteDialog
import com.cedifie.lendapp.utils.dialog.BindCardOtherDialog
import com.cedifie.lendapp.utils.dialog.BindCardSubmitDialog
import com.cedifie.lendapp.utils.dialog.BindCardSubmitWarningDialog
import com.cedifie.lendapp.utils.event.CedEventManager
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lib_baseadapter.CEDOnItemChildClickListener
import com.lib.base.utils.DensityUtils
import org.json.JSONObject

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/24 10:41
 * @Annotation：流程 - 绑卡页面（法语地区）
 */
class CedStepAccountFm: MvpFm<ICedAccountView, CedAccountPresenterImpl>(),ICedAccountView {
    private var _binding: FmStepAccountBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "binding is null"
    )
    //账户列表
    private var accountAdapter: CedStepAccountAdapter? = null

    override fun getCedRootView(inflater: LayoutInflater): View {
        _binding = FmStepAccountBinding.inflate(inflater)
        return binding.root
    }
    override fun initCedView() {
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#00000000"))
        initCedRecyclerView()
    }

    override fun initCedListener() {
        //新增
        _binding?.addLayout?.setOnClickListener {
            showCedBindCardDialog()
        }
        //提交
        _binding?.btnSubmit?.setOnClickListener {
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_STEP_ACCOUNT_CONFIRM_SUBMIT,"")
            checkCedSubmit()
        }
    }

    override fun initCedData() {
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_STEP_ACCOUNT_START,"")
        showCedLoading(getString(R.string.loading))
        mvpPresenter?.loadCedAccountListAction()
    }

    override fun createMvpPresenter(): CedAccountPresenterImpl {
        return CedAccountPresenterImpl(requireContext())
    }

    /**
     * 初始化绑卡列表
     */
    private fun initCedRecyclerView() {
//        _binding?.recyclerView.setHasFixedSize(true)
        _binding?.recyclerView?.isNestedScrollingEnabled = false
        _binding?.recyclerView?.isFocusableInTouchMode = false //不需要焦点
        _binding?.recyclerView?.layoutManager = LinearLayoutManager(context)
        accountAdapter = CedStepAccountAdapter(_binding?.recyclerView)
        val topDecoration = DensityUtils.dp2px(14f)
        _binding?.recyclerView?.addItemDecoration(LinearSpacingItemDecoration(0,0,topDecoration,topDecoration))
        _binding?.recyclerView?.adapter = accountAdapter
        _binding?.recyclerView?.itemAnimator = DefaultItemAnimator()
        accountAdapter?.setOnItemChildClickListener(CEDOnItemChildClickListener { _, childView, position ->
            when(childView.id){
                R.id.editLayout -> {//编辑
                    showCedBindCardDialog()
                }
                R.id.btnDelete -> {//删除
                    showCedDeleteDialog(position)
                }
            }
        })
    }

    /**
     * 检查提交
     */
    private fun checkCedSubmit(){
        var count = 0
        accountAdapter?.let { adapter ->
            adapter.data.forEach {
                //不是编辑类型
                if (!it.optBoolean("isEdit",true)){
                    count += 1
                }
            }
        }
        //只有一个账户，需要提示
        if (count <= 1){
            showSubmitWarningDialog()
            return
        }
        //预览所有账户列表
        showCedConfirmDialog()
    }

    /**
     * 设置已绑定的账户列表
     */
    override fun showCedAccountList(accountList: ArrayList<JSONObject>) {
        accountAdapter?.data = accountList
    }

    /**
     * 提交按钮是否可点击
     */
    override fun showCedSubmitButton(isEnable: Boolean) {
        if (isEnable){
            _binding?.btnSubmit?.isEnabled = true
            _binding?.btnSubmit?.alpha = 1f
        } else {
            _binding?.btnSubmit?.isEnabled = false
            _binding?.btnSubmit?.alpha = 0.4f
        }
    }

    /**
     * 添加绑卡dialog
     */
    private fun showCedBindCardDialog(){
        HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_USER_ACCOUNT_ADD,"StepAccount Page")
        val bindCardDialog = BindCardAddDialog(context,"StepAccount Page",object : BindCardAddDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                mvpPresenter?.submitCedBindAccountAction(phoneNumber,typeObj.optString("value"))
            }
        })
        bindCardDialog.setCancelable(true)
        bindCardDialog.setCanceledOnTouchOutside(false)
        bindCardDialog.show()
    }

    /**
     * 提示绑定另一个渠道账户
     */
    override fun showCedBingAccountOtherDialog(otherInfo: JSONObject) {
        val replaceDialog = BindCardOtherDialog(context,"StepAccount Page",object : BindCardOtherDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.btnRight){//添加
                    mvpPresenter?.submitCedBindAccountAction(otherInfo.optString("walletMobile"),otherInfo.optString("value"), "YES")
                }
            }
        })
        replaceDialog.setCancelable(true)
        replaceDialog.setCanceledOnTouchOutside(false)
        replaceDialog.show()
        replaceDialog.setBindAccountInfo(otherInfo)
    }


    /**
     * 删除提示
     */
    private fun showCedDeleteDialog(position: Int){
        accountAdapter?.let {
            val item = it.getItem(position)
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_USER_ACCOUNT_DELETE,item.optString("id"))
            val deleteDialog = BindCardDeleteDialog(context,"StepAccount Page", object : BindCardDeleteDialog.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view?.id == R.id.btnRight){
                        mvpPresenter?.deleteCedAccountAction(item.optString("id"))
                    }
                }
            })
            deleteDialog.setCancelable(true)
            deleteDialog.setCanceledOnTouchOutside(false)
            deleteDialog.show()
            deleteDialog.setBindAccountInfo(item)
        }
    }

    /**
     * 只有一个账户警告提示
     */
    private fun showSubmitWarningDialog(){
        val warningDialog = BindCardSubmitWarningDialog(context,"StepAccount Page",object : BindCardSubmitWarningDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view?.id){
                    R.id.btnNoMore -> {//提交(不再有账户)
                        //立即上报
                        CedEventManager.getInstance().updateCedEventsNow()
                        // TODO: 发送通知，更新主流程
                        val act = context as CedStepAct
                        act.showCedSubmitSuccess()
                    }
                    R.id.btnAdd -> {//继续添加
                        showCedBindCardDialog()
                    }
                }
            }
        })
        warningDialog.setCancelable(true)
        warningDialog.setCanceledOnTouchOutside(false)
        warningDialog.show()
    }

    /**
     * 确认dialog
     */
    private fun showCedConfirmDialog(){
        val submitDialog = BindCardSubmitDialog(context,object : BindCardSubmitDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.btnConfirm){
                    HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_USER_ACCOUNT_SUBMIT_TIPS_CONFIRM,"")
                    //立即上报
                    CedEventManager.getInstance().updateCedEventsNow()
                    // TODO: 发送通知，更新主流程
                    val act = context as CedStepAct
                    act.showCedSubmitSuccess()
                }
            }
        })
        submitDialog.show()
        accountAdapter?.let {
            submitDialog.setBindAccountList(it.data)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_STEP_ACCOUNT_END,"")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}